package site.kuangzhang.probe.handler;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import site.kuangzhang.probe.pojo.Miner;
import site.kuangzhang.probe.util.Http;
import site.kuangzhang.probe.util.IOUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;

import static site.kuangzhang.probe.util.StaticValue.L3_PLUSH;


/**
 * 蚂蚁矿机采集程序 ,
 * L3+ T9
 */
public class AntminerHandler implements Handler{

	private static final Logger LOG = Logger.getLogger("AmtminerHandler");


	private Miner miner;

	/**
	 * 每次new调用
	 *
	 * @param miner
	 */
	public AntminerHandler(Miner miner) {
		this.miner = miner;
	}


	public void execute() {

		CredentialsProvider provider = new BasicCredentialsProvider();
		provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("root", "root"));

		HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

		//获取机器型号等信息
		HttpResponse execute = null;
		try {
			execute = client.execute(new HttpGet("http://" + miner.getIp() + "/cgi-bin/get_system_info.cgi"));

			JSONObject json = JSONObject.parseObject(IOUtil.getContent(execute.getEntity().getContent(), "utf-8"));

			miner.setType(json.getString("minertype"));
			miner.setNetProtocol(json.getString("nettype"));
			miner.setMacAddress(json.getString("macaddr"));

		} catch (IOException e) {
			LOG.log(Level.WARNING, "get system info err");
		}


		//获取详细信息

		try {
			execute = client.execute(new HttpGet("http://" + miner.getIp() + "/cgi-bin/minerStatus.cgi"));
			String html = IOUtil.getContent(execute.getEntity().getContent(), "utf-8");

			Document parse = Jsoup.parse(html);

			try {
				miner.setElapsed(parse.getElementById("ant_elapsed").text());
			} catch (Exception e) {
				LOG.log(Level.WARNING, "elapsed get err ");
			}

			try {
				miner.setRate(Double.parseDouble(parse.getElementById("ant_ghs5s").text().replace(",", "")));
			} catch (Exception e) {
				LOG.log(Level.WARNING, "rate get err");
			}

			Element cbi = parse.getElementById("ant_devs");


			int[] temps = cbi.getAllElements().stream().filter(element -> element.attr("id").equals("cbi-table-1-temp2")).mapToInt(e -> {
				String v = e.text();

				if (L3_PLUSH.equals(miner.getType())) {
					v = v.split(":")[2].trim();
				}

				try {
					return Integer.parseInt(v);
				} catch (NumberFormatException ex) {
					return 0;
				}
			}).toArray();

			int max = 0;
			if(temps!=null && temps.length>0){
				max = Arrays.stream(temps).reduce(Integer::max).getAsInt();
			}

			miner.setTemp(max);
			System.out.println("获取 ： " + miner.getIp()+" 成功！");
		} catch (IOException e) {
			Logger.getLogger("AmtminerHandler").log(Level.WARNING, "get status info err");
		}
	}


}
